package com.edu.demo.controller;

import com.edu.demo.entity.Teacher;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.service.ITeacherService;
import com.edu.demo.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {


    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PostMapping("/update")
    @PreAuthorize("@ps.hasPerm('tea:myinfo:update')")
    public AjaxResult updateMyInfos(@RequestBody Teacher teacher){
        Teacher teacher1 = SecurityUtils.getTeacher();
        if(teacher1.getId()!=teacher.getId())
                return AjaxResult.error("不能更新其他的老师信息");
        teacher.setPassword(null);
        boolean b = teacherService.updateById(teacher);
        if(b)return AjaxResult.success();
        else return AjaxResult.error("更新失败");

    }

    @PostMapping("/updatePassword")
    @PreAuthorize("@ps.hasPerm('tea:myinfo:update')")
    public AjaxResult updatePassword(@RequestBody Map<String,String> para){
        Teacher teacher1 = SecurityUtils.getTeacher();
        String oldPassword = para.get("oldPassword"),newPassword = para.get("newPassword");
        Integer teaId = Integer.parseInt( para.get("id"));
        if(teacher1.getId()!=teaId)
            return AjaxResult.error("不能更新其他的老师信息");
        boolean matches = passwordEncoder.matches(oldPassword, teacher1.getPassword());
        if(matches) {
            teacher1.setPassword(passwordEncoder.encode(newPassword));
            boolean b = teacherService.updateById(teacher1);
            if (b) return AjaxResult.success();
        }
         return AjaxResult.error("旧密码错误");

    }

}
